/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.star.admin.controller;

import com.star.common.CommonUtil;
import com.star.common.PostData;
import com.star.common.RenderModel;
import com.star.common.UserRole;
import com.start.model.PostModel;
import hapax.Template;
import hapax.TemplateDataDictionary;
import hapax.TemplateDictionary;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

/**
 *
 * @author Administrator
 */
public class AdminCheckNewsController extends HttpServlet {
    private static final Logger logger = Logger.getLogger(AdminCheckNewsController.class);
    private static final int NEWS_PER_PAGE = 10;
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handle(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handle(req, resp);
    }
    
    private void handle(HttpServletRequest req, HttpServletResponse resp) {
        try {
            if(!CommonUtil.checkSession(req, resp))
                return;            
            processs(req, resp);
        } catch (IOException ex) {
            logger.error("AdminCheckNewsController.handle:" + ex.getMessage(), ex);
        }
    }
    
    private void processs(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String content;
        String pathInfo = (req.getPathInfo() == null) ? "" : req.getPathInfo();
        switch (pathInfo) {
            default:
                content = renderIndexPage(req, resp);
        }
        CommonUtil.out(content, resp);
    }
    
    
    private String renderIndexPage(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String content = "";   
        try {
            TemplateDataDictionary dic = TemplateDictionary.create();
            if (!CommonUtil.checkAccess(req, UserRole.POST_PUBLIC)) {
                resp.sendRedirect("/");
                return "";
            }
            
            dic.setVariable("HEADER", CommonUtil.getAdminHeader());
            dic.setVariable("FOOTER", CommonUtil.getAdminFooter());
            dic.setVariable("MENU", CommonUtil.getAdminMenu(req));
            dic.setVariable("SIDEBAR", CommonUtil.getAdminSidebar(req, "check_news"));
            dic.setVariable("PAGE_TITLE", "Duyệt tin tức");
            
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
//            if(CommonUtil.checkAccess(req, UserRole.NEWS_PUBLIC)){
//                dic.showSection("SHOW_LIST_NEWS");
//                int page = 1;
//                String p = req.getParameter("p") == null ? "1" : req.getParameter("p");
//                try {
//                    page = Integer.parseInt(p);
//                } catch (NumberFormatException e) {
//                }                
//                NewsModel newsModel = NewsModel.getInstance();                  
//                List<NewsData> lstNewsData = newsModel.getNews(0, -1, "", "", "0", "", "", "");  
//                if (lstNewsData != null && !lstNewsData.isEmpty()) {                    
//                    for(int i = (page - 1) * NEWS_PER_PAGE; i < page * NEWS_PER_PAGE; i++) {
//                        if(i == lstNewsData.size())
//                            break;
//                        NewsData newsData = lstNewsData.get(i);
//                        TemplateDataDictionary section = dic.addSection("LIST_NEWS");                    
//                        section.setVariable("NEWS_ID", newsData.getId());  
//                        section.setVariable("NEWS_TITLE", newsData.getTitle());                     
//                        Date d = new Date(newsData.getCreated());
//                        section.setVariable("CREATED", sdf.format(d));
//                        section.showSection("WARNING");                        
//                    }
//                }
//                
//                int count = lstNewsData.size();
//                String pageNavi = CommonUtil.getPageNavi(page, count, NEWS_PER_PAGE, "?" + req.getQueryString());
//                dic.setVariable("PAGENAVI", pageNavi);
//            }
            
            if(CommonUtil.checkAccess(req, UserRole.POST_PUBLIC)){
                dic.showSection("SHOW_POST_LIST");
                int page = 1;
                String p = req.getParameter("p2") == null ? "1" : req.getParameter("p2");
                try {
                    page = Integer.parseInt(p);
                } catch (NumberFormatException e) {
                }
                
                PostModel postModel = PostModel.getInstance();                
                List<PostData> lstPost = postModel.getPost(0, -1, "", "", "", "", "0", "", ""); 
                if (lstPost != null && !lstPost.isEmpty()) { 
                    for(int i = (page - 1) * NEWS_PER_PAGE; i < page * NEWS_PER_PAGE; i++) {
                        if(i == lstPost.size())
                            break;
                        PostData postData = lstPost.get(i);
                        TemplateDataDictionary addSection = dic.addSection("POST_LIST");
                        addSection.setVariable("POST_ID", postData.getId());
                        addSection.setVariable("POST_TITLE", postData.getTitle());
                        Date d = new Date(postData.getCreated());
                        addSection.setVariable("CREATED", sdf.format(d));
                        addSection.showSection("WARNING"); 
                    }
                }
                
                int count = lstPost.size();
                String pageNavi = getPageNaviPost(page, count, NEWS_PER_PAGE, "?" + req.getQueryString());
                dic.setVariable("PAGENAVI_POST", pageNavi);
            }           
                                                              
            Template template = RenderModel.getAdminCTemplate("index_page");
            content = template.renderToString(dic);
        } catch (Exception ex) {
            logger.error("AdminIndexController.renderIndexPage: " + ex.getMessage(), ex);
        }
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
        return content;
    }
    
    
    public static String getPageNaviPost(int current, int postCount, int postPerPage, String link) {
        Pattern p = Pattern.compile("-?\\d+");
        Matcher m = p.matcher(link);
        while (m.find()) {
            String tmp = m.group();
            link = link.replace("?p2=" + tmp, "?")
                    .replace("&p2=" + tmp, "");
        }
        if (link.lastIndexOf("?") == link.length() - 1) {
            link = link.replace("?", "");
        }

        String html = "";
        String paramDelimiter = link.contains("?") ? "&" : "?";
        if (postCount > postPerPage) {
            int totalPage = postCount / postPerPage + (postCount % postPerPage > 0 ? 1 : 0);
            int PAGEGAP = 3;
            String li = "";
            for (int i = 1; i <= totalPage; i++) {
                String pageNum;
                String url;
                if (i > 1 && i < totalPage && Math.abs(i - current) > PAGEGAP) {
                    i = i < current ? current - PAGEGAP : totalPage - 1;
                    pageNum = "...";
                    url = "#";
                } else {
                    pageNum = String.valueOf(i);
                    url = link + paramDelimiter + "p2=" + i;
                }
                li += "<li class=\"" + (current == i ? "active" : "") + "\">"
                        + "<a href=\"" + url + "\">" + pageNum + "</a>"
                        + "</li>";
            }
            String firstPage = "<li class=\"" + (current == 1 ? "disabled" : "") + "\">"
                    + "<a href=\"" + link + paramDelimiter + "p2=1\">&laquo;</a>"
                    + "</li>";
            String lastPage = "<li class=\"" + (current == totalPage ? "disabled" : "") + "\">"
                    + "<a href=\"" + link + paramDelimiter + "p2=" + totalPage + "\">&raquo;</a>"
                    + "</li>";
            html = "<ul style=\"margin: 0;\" class=\"pagination pagination-md pull-right\">" + firstPage + li + lastPage + "</ul>";
        }
        return html;
    }
}
